package knapsackProblem;

public class KnapsackProblem {
    public static void main(String[] args) {
        // 物品重量和价值
        int[] weight = {1, 4, 3};
        int[] value = {1500, 3000, 2000};
        // 背包最大重量
        int maxWeight = 4;
        //物品的个数
        int n = value.length;

        //创建二维数组记录价值
        int[][] v = new int[n + 1][maxWeight + 1];
        //创建二维数组记录物品是否被选中
        int[][] path = new int[n + 1][maxWeight + 1];
        //初始化二维数组
        for (int i = 0; i < v.length; i++) {
            v[i][0] = 0;
        }
        for (int i = 0; i < v[0].length; i++) {
            v[0][i] = 0;
        }

        for (int i = 1; i < v.length; i++) {
            for (int j = 1; j < v[i].length; j++) {
                if (j < weight[i - 1]) {
                    v[i][j] = v[i - 1][j];//背包装不下新物品 只能不装 还是上次的价值
                } else {
                    if (v[i - 1][j] < v[i - 1][j - weight[i - 1]] + value[i - 1]) {
                        v[i][j] = v[i - 1][j - weight[i - 1]] + value[i - 1];
                        path[i][j] = 1;
                    } else {
                        v[i][j] = v[i - 1][j];
                    }
                    //v[i][j] = Math.max(v[i - 1][j], v[i - 1][j - weight[i - 1]] + value[i - 1]);
                }
            }
        }
        //展示价值矩阵
        for (int i = 0; i < v.length; i++) {
            for (int j = 0; j < v[i].length; j++) {
                System.out.print(v[i][j] + " ");
            }
            System.out.println();
        }

        //展示path矩阵
        while (n > 0 && maxWeight > 0) {
            if (path[n][maxWeight] == 1) {
                System.out.println("第" + n + "个物品被选中");
                maxWeight -= weight[n - 1];
            }
            n--;

        }
    }
}
